<template>
  <div class="goods-content">
    <div class="auth-modal-btns" v-if="$route.query?.review !== 'true'">
      <p v-if="product?.modelFile?.modelFileList?.length > 0" @click="clickAuthModal(3)">模型下载</p>
      <!-- <p v-else @click="clickAuthModal(1)">申请模型</p> -->
      <span class="jzt-flex-center ml10" v-if="product.showUserMobile">
        <el-button type="primary" class="jzt-button" link @click="isShowPhone = !isShowPhone">
          <el-icon class="mr4" v-if="isShowPhone"><View /></el-icon>
          <el-icon class="mr4" v-else><Hide /></el-icon>
        </el-button>
        <span v-if="isShowPhone">技术支持：{{ product.showUserMobile || "-" }}</span>
      </span>
    </div>
    <div class="goods-image">
      <div class="shop-id">
        <span>商品ID: {{ product.productId }}</span>
        <img :src="copyImg" @click="handelCopyProductId(product.productId)" />
      </div>

      <!-- 预览大图 -->
      <div
        class="large"
        v-show="show && images[currIndex]?.split('.')[images[currIndex]?.split('.').length - 1] !== 'mp4'"
        :style="[{ backgroundImage: `url(${images[currIndex]})` }, bgPosition]"
      ></div>
      <!-- 商品大图 -->
      <div class="middle">
        <!-- 商品大图 -->
        <video
          class="video"
          v-if="images[currIndex]?.split('.')[images[currIndex]?.split('.').length - 1] === 'mp4' && videoUrl"
          :src="videoUrl"
          controls
          style="width: 100%; height: 100%"
        />
        <div v-else style="position: relative">
          <img class="pic" ref="target" :src="images[currIndex]" alt="" />
          <!-- 鼠标进入图片的遮罩 -->
          <div
            class="layer"
            v-show="show && images[currIndex]?.split('.')[images[currIndex]?.split('.').length - 1] !== 'mp4'"
            :style="[position]"
          ></div>
        </div>
      </div>
      <!-- 缩略小图 -->
    </div>
    <div
      v-if="product.delistTime && new Date(product.delistTime).getTime() > new Date().getTime()"
      class="countdown"
      :class="{
        'countdown-red': product.delistType == 2,
        'countdown-orange': product.delistType == 1
      }"
    >
      <div>
        商品下架倒计时
        <div class="day">{{ getTime() }}天</div>
        <Countdown :delistTime="product.delistTime" :delistType="product.delistType" @getTime="getTime" />
      </div>
      <div class="tag">{{ product.delistType == 2 ? "停产" : "暂时下架" }}</div>
    </div>
    <div class="box-over">
      <div class="small">
        <div v-for="(img, i) in images" :key="img" :class="{ active: i === currIndex }" class="small-box" :alt="i">
          <!-- v-show="i <= activeIndex * 4 && i >= (activeIndex - 1) * 4" -->
          <video
            v-if="i === 0 && videoUrl"
            @mouseenter="handelMouseenter(i)"
            :src="videoUrl"
            controls
            style="width: 134px; height: 134px; margin-right: 20px"
          />
          <!-- 鼠标移入商品大图旁边的小图商品大图位置就会显示该图 -->
          <img v-else @mouseenter="handelMouseenter(i)" :src="img" alt="" />
        </div>
        <div class="font" @click="upIndex" v-if="activeIndex > 1">
          <el-icon>
            <ArrowLeft />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- 申请授权弹窗 -->
    <el-dialog v-model="dialogVisible" title="" :width="550" align-center append-to-body>
      <h3 class="jzt-flex-center" v-if="modelDetail?.modelStatus === 2" style="line-height: 80px">已建模完成</h3>
      <div v-else style="height: 40px"></div>

      <template #header>
        <p style="color: #3d3d3d">
          模型授权信息
          <span class="f12" style="color: #86909c">（暂无模型授权信息请点击申请授权）</span>
        </p>
      </template>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button v-if="modelDetail?.modelStatus === 0" class="yyx-btn" type="primary" style="width: 320px" @click="clickApply"
            >申请授权模型</el-button
          >
          <el-button v-else-if="modelDetail?.modelStatus === 1" class="yyx-btn" type="primary" disabled style="width: 320px">
            已提交申请授权模型
          </el-button>
          <el-button v-else class="yyx-btn" type="primary" style="width: 320px" @click="dialogVisible = false">
            我知道了
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 模型下载 -->
    <el-dialog v-model="modelDownload" title="模型下载" width="440px" align-center append-to-body>
      <div class="modelDownload">
        <div class="modelDownload_text">模型授权链接或型号</div>
        <div class="modelDownload_center">
          <el-input readonly :rows="3" :value="product?.modelFile?.modelRemark" type="textarea"></el-input>
        </div>
        <div class="modelDownload_foot">
          <div class="modelDownload_foot_item" v-for="item in product?.modelFile?.modelFileList || []" :key="item.fileId">
            <img src="@/assets/images/fileicon.png" style="width: 50px; height: 50px; margin-left: 8px" />
            <div class="modelDownload_footitem_center">
              <div class="modelDownload_footitem_toptext">
                <el-tooltip :content="item.fileName" placement="bottom" effect="light">
                  {{ item.fileName }}
                </el-tooltip>
              </div>
              <div class="modelDownload_footitem_downtext">文件大小：{{ Math.round(item.size / 1024) }}KB</div>
            </div>
            <div class="modelDownload_foot_icon">
              <img src="@/assets/images/finish.png" style="width: 16px; height: 16px; margin-left: 8px" v-if="item === 1" />
              <img
                src="@/assets/images/xiazai.png"
                style="width: 16px; height: 16px; margin-left: 8px"
                v-else
                @click="download(item)"
              />
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { reactive, ref, watch } from "vue";
import { useMouseInElement } from "@vueuse/core";
import Countdown from "@/components/Countdown/index.vue";
import {
  getModelDetail,
  applyModel,
  getLabelList,
  collectConfirm,
  collectCancel,
  addPproductLabel,
  delPproductLabel
} from "@/api/shopHome/detail";
import { ElMessage } from "element-plus";
import copyImg from "@/assets/images/copy.png";

export default {
  name: "GoodsImage",
  components: {
    Countdown
  },
  props: {
    images: {
      type: Array,
      default: () => []
    },
    product: {
      type: Object
    },
    SKU: {
      type: Function
    },
    videoUrl: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      copyImg,
      activeIndex: 1,
      dialogVisible: false,
      modelDownload: false,
      sourceType: 1,
      modelDetail: {},
      skuObj: {},
      collectType: [],
      oldSelects: [],
      styleList: [], //款式风格
      isCollect: 0, //是否收藏 0-未收藏 1-已收藏
      isShowPhone: false //是否显示电话号码
    };
  },
  watch: {
    product: {
      handler(newVal, oldVal) {
        this.isCollect = this.product.collectState;
        this.collectType = this.product.collectLabelIds;
        this.oldSelects = this.product.collectLabelIds;
      }
    }
  },
  async mounted() {
    // const Enum = await getLabelList(); //查询收藏标签列表
    // this.styleList = Enum.data;
    // console.log("这是标签列表", this.styleList);
  },
  methods: {
    //申请建模
    clickApply() {
      // applyModel({
      //   skuId: this.skuObj.skuId,
      //   applyType: this.product.sourceType || 1,
      //   productId: this.product.productId
      // }).then(res => {
      //   if (res.code === 200) {
      //     ElMessage({
      //       message: "申请成功",
      //       type: "success",
      //       offset: 60
      //     });
      //     this.dialogVisible = false;
      //   } else {
      //     ElMessage({
      //       message: res.msg,
      //       type: "error",
      //       offset: 60
      //     });
      //   }
      // });
    },
    async clickAuthModal(type) {
      // sourceType-1-工厂，系统授权模型
      // sourceType-2-自有，自有授权模型
      if (type == 3) {
        this.modelDownload = true;
      } else {
        this.sourceType = type;
        const skuObj = this.SKU();
        this.skuObj = skuObj;
        const res = await getModelDetail({ productId: skuObj?.productId, applyType: type });
        res.code === 200 && (this.modelDetail = res.data);
        this.dialogVisible = true;
      }
    },
    //模型文件下载
    download(item) {
      const a = document.createElement("a");
      let href = item.url;

      a.download = item.fileName; // 跨域不生效
      a.style.display = "none";
      a.href = href;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(href);
    },
    compareArrays(arr1, arr2) {
      let added = arr2.filter(element => !arr1.includes(element));
      let removed = arr1.filter(element => !arr2.includes(element));
      return { added, removed };
    },
    handelCopyProductId(id) {
      const textarea = document.createElement("textarea");
      textarea.readOnly = true;
      textarea.style.position = "absolute";
      textarea.style.left = "-9999px";
      textarea.value = id;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("Copy");
      document.body.removeChild(textarea);
      this.$message.success("复制成功");
    },
    handelMouseenter(currIndex) {
      this.currIndex = currIndex;
    },
    upIndex() {
      this.activeIndex--;
    },
    next() {
      this.activeIndex++;
    },
    getTime() {
      const now = new Date();
      const futureDate = new Date(this.product.delistTime).getTime();
      const diff = futureDate - now;
      const day = Math.floor(diff / 1000 / 60 / 60 / 24);
      return day > 0 ? day : 0;
    }
  },
  setup(props) {
    // 控制预览大图与遮罩层的显示与隐藏
    const show = ref(false);
    // 控制商品大图显示那张图片
    const currIndex = ref(0);
    // ref 获取 DOM 元素
    const target = ref(null);
    // 记录遮罩半透明图在商品大图中的坐标位置
    const position = reactive({
      top: 0,
      left: 0
    });
    // 记录遮罩层做覆盖的区域在预览时的预览大图的坐标位置
    const bgPosition = reactive({
      backgroundPositionX: 0,
      backgroundPositionY: 0
    });
    // 获得的图片容器的宽度
    const middleWidth = ref(0);
    // 第三方 vueuse 提供的方法 useMouseInElement 获取鼠标在某块区域的坐标
    const { elementX, elementY, isOutside } = useMouseInElement(target);
    // 侦听器监测鼠标进入商品大图时的坐标从而操纵遮罩层和预览大图的效果
    watch([elementX, elementY, isOutside], () => {
      // isisOutside.value 为 true 的时候代表鼠标未进入目标元素，为 false 时代表鼠标进入目标元素
      // 为 true 是不记录坐标以免损耗性能
      // 获取dom
      const dom = document.querySelectorAll(".middle");
      // console.log(dom, "获取的dom");
      const widths = dom.clientWidth;
      middleWidth.value = widths;

      if (isOutside.value) {
        // 鼠标未进入目标元素不显示遮罩层和预览大图
        show.value = false;
        return;
      }
      // 鼠标进入目标元素显示遮罩层和预览大图
      show.value = true;
      // 判断边界值，根据遮罩层大小、商品图片大小判断
      // left 的边界值（左、右）
      if (elementX.value < 100) {
        position.left = 0;
      } else if (elementX.value > target.value.clientWidth - 100) {
        position.left = target.value.clientWidth - 200;
      } else {
        position.left = elementX.value - 100;
      }
      // top 的边界值（上、下）
      if (elementY.value < 100) {
        position.top = 0;
      } else if (elementY.value > target.value.offsetHeight - 100) {
        position.top = target.value.offsetHeight - 200;
      } else {
        position.top = elementY.value - 100;
      }
      // 遮罩层所覆盖的商品图片部分在预览大图中的坐标，加单位
      bgPosition.backgroundPositionY = -position.top * 2 + "px";
      bgPosition.backgroundPositionX = -position.left * 2 + "px";
      // 遮罩层相对于商品大图左上角坐标，加单位
      position.top += "px";
      position.left += "px";

      // console.log(position);
      // console.log({ x: elementX.value, y: elementY.value });
    });
    // 返回给模板使用
    return { currIndex, show, target, position, bgPosition };
  }
};
</script>

<style lang="scss">
.collect-star-popper {
  &.el-popper {
    font-size: 12px !important;
  }
}
</style>
<style scoped lang="scss">
@use "@/assets/styles/mixin";
:deep(.el-textarea__inner) {
  background-color: #f2f3f5 !important;
}
:deep(.el-popover.el-popper) {
  font-size: 12px !important;
}
.goods-content {
  margin-right: 20px;
  // flex: 1;
  width: 600px;
  .auth-modal-btns {
    display: flex;
    margin-bottom: 20px;
    color: #3d3d3d;
    font-size: 14px;
    p {
      cursor: pointer;
    }
  }
}

.model-list-wrap {
  max-height: 400px;
  overflow-y: auto;
  & > div {
    display: flex;
    .left {
      width: 110px;
      height: 110px;
    }
    .right {
      flex: 1;
      padding-left: 16px;
      & > div {
        display: flex;
        margin-bottom: 10px;
        .el-input,
        .el-textarea {
          flex: 1;
        }
      }
      p {
        width: 90px;
        margin-right: 10px;
        font-size: 14px;
        margin-top: 5px;
      }
    }
  }
}

.goods-image {
  // width: 400px;
  // height: 400px;
  position: relative;
  display: flex;
  flex-direction: column;
  z-index: 20;
  background-color: #f9f9f9;
  border-radius: 4px;
  .shop-id {
    @include mixin.flex-inline-flex;
    position: absolute;
    left: 0;
    top: 0;
    width: fit-content;
    min-width: 138px;
    height: 28px;
    padding: 0 10px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 0 0 10px 0;
    color: #86909c;
    img {
      width: 14px;
      height: 14px;
      margin-left: 5px;
      cursor: pointer;
    }
  }

  .collect {
    position: absolute;
    right: 10px;
    top: 10px;
    & > div {
      display: flex;
      align-items: center;
      background-color: #4e5969cc;
      border-radius: 16px;
      padding-left: 8px;
      img {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
      :deep(.el-divider--vertical) {
        margin-right: 0;
      }
      & > div.select {
        padding: 4px 8px 4px 0;
        :deep(.el-select__selected-item.el-tooltip__trigger.el-tooltip__trigger) {
          .el-tag {
            padding: 0;
          }
        }
        :deep(.el-tag) {
          background-color: transparent;
          color: white;
        }
        :deep(.el-select__placeholder) {
          color: white;
        }
        :deep(.el-select__caret) {
          color: white;
        }
        :deep(.el-select__wrapper) {
          background-color: transparent !important;
          border: none;
          box-shadow: none;
        }
      }
    }
  }

  .large {
    position: absolute;
    top: 50px;
    left: 640px;
    width: 400px;
    height: 400px;
    z-index: 999;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }

  .middle {
    // width: 400px;
    height: 600px;
    position: relative;
    cursor: move;
    z-index: -1;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: auto;
      height: auto;
      max-height: 500px;
      border-radius: 5px;
    }

    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
}

.box-over {
  width: 100%;
  overflow: hidden;

  .small {
    width: 100%;
    margin-top: 10px;
    position: relative;
    white-space: nowrap;
    padding: 10px 0;
    overflow-x: auto;
    overflow-y: auto;

    .font {
      position: absolute;
      left: 0;
      width: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 140px;
      cursor: pointer;
      background: #f9f9f9;
      box-shadow: -5px 0px 5px 0px rgba(78, 89, 105, 0.1);
      border-radius: 0px 4px 4px 0px;
    }

    .next {
      position: absolute;
      width: 16px;
      display: flex;
      cursor: pointer;
      align-items: center;
      justify-content: center;
      height: 140px;
      background: #f9f9f9;
      box-shadow: -5px 0px 5px 0px rgba(78, 89, 105, 0.1);
      border-radius: 0px 4px 4px 0px;
      left: 584px;
    }

    .small-box {
      // width: 140px;
      // height: 140px;
      width: 134px;
      height: 134px;
      border-radius: 4px 4px 4px 4px;
      margin-right: 20px;
      cursor: pointer;
      border: 2px solid transparent;
      display: inline-block;
      box-shadow: #3d3d3d80 6px 2px 6px;

      img {
        width: 100%;
        border-radius: 4px 4px 4px 4px;
        height: 100%;
      }

      &:hover,
      &.active {
        border: 2px solid #ff8928;
      }
    }
  }
}

img {
  width: 100%;
  height: 100%;
}

[class*="countdown"] {
  align-items: center;
  height: 50px;
  display: flex;
  color: white;
  padding: 0 16px;
  justify-content: space-between;

  position: absolute;
  bottom: 130px;
  z-index: 22;
  width: 600px;
  box-sizing: border-box;

  .time {
    background: white;
    height: 18px;
    padding: 0 6px;
  }

  > div:nth-child(1) {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .tag {
    border: 1px solid white;
    border-radius: 4px;
    height: 18px;
    font-size: 12px;
    line-height: 18px;
    padding: 0 6px;
  }

  .day {
    padding: 0 4px;
    background: white;
    border-radius: 4px;
    font-size: 12px;
    height: 18px;
    line-height: 18px;
  }
}

.countdown-red {
  background: #e55151;

  .day {
    color: #e55151;
  }
}

.countdown-orange {
  background: #e5a351;

  .day {
    color: #e5a351;
  }
}
.modelDownload {
  .modelDownload_text {
    margin-top: 8px;
    height: 22px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #4e5969;
    text-align: left;
  }
  .modelDownload_center {
    width: 390px;
    height: 64px;
    border-radius: 0px 0px 0px 0px;
    // border: 1px solid #e1e6ed;
    margin-top: 10px;
    :deep(.el-textarea) {
      width: 100%;
      height: 100%;
      .el-textarea__inner {
        background-color: white !important;
      }
    }
  }
  .modelDownload_foot {
    margin-top: 20px;
    height: 238px;
  }
}
.modelDownload_foot_item {
  background: #f5f7fa;
  height: 66px;
  border-radius: 4px 4px 4px 4px;
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-items: flex-start;
  position: relative;
  .modelDownload_foot_icon {
    position: absolute;
    top: 8px;
    right: 8px;
  }
  .modelDownload_footitem_center {
    margin-left: 10px;
  }
  .modelDownload_footitem_toptext {
    width: 300px;
    height: 22px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #3d3d3d;
    overflow: hidden; /*内容超出后隐藏*/
    text-overflow: ellipsis; /*超出内容显示为省略号*/
    white-space: nowrap; /*文本不进行换行*/
  }
  .modelDownload_footitem_downtext {
    height: 22px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #86909c;
  }
}
.modelDownload_counter {
  // margin: 8px 81px 8px 8px;
  width: 100%;
  height: 100%;
  font-family: Source Han Sans;
  font-weight: 400;
  font-size: 14px;
  color: #86909c;
  text-align: left;
  display: flex;
  justify-content: space-evenly;
  flex-direction: column;
  overflow-y: auto;
}
</style>
